<?php

namespace App\Repositories;
use App\Interfaces\CouponService;
use App\Interfaces\OrderService;
use App\Models\UserCoupon;
use App\Models\Coupon;
use App\Models\CouponType;
use App\Models\Goods;
use App\Exceptions\Interfaces\CouponServiceException;
use Auth,Log;
use Illuminate\Database\Eloquent\Collection;

class CouponRepository implements  CouponService
{


    /**
     * 获取用户已领取的优惠券信息
     * @param int $user_id      用户id
     */
    public function getUserAvailableCouponByUser($user_id){

        $query = UserCoupon::leftJoin('coupon', 'user_coupon.coupon_id', '=', 'coupon.id')
                ->select( 'coupon.*','user_coupon.*');

        $query = $query->whereNull('user_coupon.deleted_at');//没删除
        $query = $query->whereNull('user_coupon.use_time');//没使用
        $query = $query->where('user_coupon.user_id', $user_id);//属于该

        $query = $query->whereNull('coupon.deleted_at');//优惠券没有被删除
        $query = $query->whereRaw('coupon.start_time <= now()');//已开始
        $query = $query->whereRaw('coupon.end_time > now()');//未结束哦

        return $query->get();

    }//end func getUserAvailableCouponByUser()

    public function checkCouponIsUseable($user_id, $user_coupon_id, Collection $orderGoods,$buyGoods){

        $user_coupons = $this->getCanUseCoupon($user_id, $orderGoods,$buyGoods);

        if (count($user_coupons)>0) {
            foreach ($user_coupons as $key => $value) {

                if ($user_coupon_id == $value->id) {
                    return true;
                }//end if()
            }//end foreach()

        }//end if()
        return false;


    }//end func checkCouponIsUseable()



    /**
     * 根据要购买的商品获取用户已有优惠券中可使用的优惠券信息
     * @param int $user_id      用户id
     * @param array $cartGoods      商品数组
     * @param array $not_available_use_coupon_id      排除掉的用户优惠券id
     * @return mixed  可用的优惠券
     */
    public function getCanUseCoupon($user_id, Collection $orderGoods,$buyGoods, $not_available_use_coupon_id=''){

        //获取用户所有的优惠券
        $userCoupons = $this->getUserAvailableCouponByUser($user_id);



        //可用优惠券条件 1.订单满足优惠券满减金额限制,&&.在可用范围,商铺,品牌,分类,商品,全场通用


        $user_coupons = new Collection();


        if ($userCoupons->count()>0) {



            foreach ($userCoupons as $key => $userCoupon) {

                //根据优惠券类型判断是否可用(可用类型，1：全场通用；2：商品；3：分类；4：店铺；5：品牌)

                $total_goods_price = 0;

                $goods_type_price = 0;

                $cat_type_price = 0;

                $shop_type_price = 0;

                $brand_type_price = 0;




                foreach ($orderGoods as $key => $goods) {

                    if($goods){

                        $goods_real_price = 0.00;

                        if ($goods->discount) {

                            $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100), 0, -1));
                        }else{
                            $goods_real_price = $goods->shop_price;
                        }

                        $total_goods_price += $goods_real_price*$buyGoods[$goods->goods_id];//订单货值

                        //2. 符合可用商品

                        $goods_ids = CouponType::where('coupon_id',$userCoupon->coupon_id)->lists('use_id')->toArray();

                        if ($userCoupon->type==2){


                            if (in_array($goods->goods_id,$goods_ids)){

                                $goods_type_price += $goods_real_price*$buyGoods[$goods->goods_id];

                            }

                        }

                        if ($userCoupon->type==3){


                            if (in_array($goods->cat_id,$goods_ids)){

                                $cat_type_price += $goods_real_price*$buyGoods[$goods->goods_id];

                            }
                        }

                        if ($userCoupon->type==4){


                            if (in_array($goods->shop_id,$goods_ids)){

                                $shop_type_price += $goods_real_price*$buyGoods[$goods->goods_id];

                            }
                        }

                        if ($userCoupon->type==5){


                            if (in_array($goods->brand_id,$goods_ids)){

                                $brand_type_price += $goods_real_price*$buyGoods[$goods->goods_id];

                            }
                        }


                    }

                }


                //1. 全场通用

                if ($userCoupon->type ==1&&$total_goods_price>=$userCoupon->limit_fir){
                    $user_coupons = $user_coupons->add($userCoupon);

                }

                //2. 符合可用商品


                if($userCoupon->type ==2 &&$goods_type_price>=$userCoupon->limit_fir){

                    $user_coupons = $user_coupons->add($userCoupon);
                }

                //3. 符合可用分类


                if($userCoupon->type ==3 &&$cat_type_price>=$userCoupon->limit_fir){

                    $user_coupons = $user_coupons->add($userCoupon);
                }

                //4. 符合可用店铺


                if($userCoupon->type ==4 &&$shop_type_price>=$userCoupon->limit_fir){

                    $user_coupons = $user_coupons->add($userCoupon);
                }

                //5. 符合可用品牌


                if($userCoupon->type ==5 &&$brand_type_price>=$userCoupon->limit_fir){

                    $user_coupons = $user_coupons->add($userCoupon);
                }


            }//end foreach()

        }//end if()

        return $user_coupons;

    }//end func getCanUseCoupon



    /**
     * 使用优惠券
     * @param int $user_id      用户id
     * @param int $coupon_id    优惠券id
     * @return mixed  包含: 1.用户所有的收货地址
     */
    public function useCoupon($user_id, $user_coupon_id){

        $coupons = UserCoupon::select('user_coupon.id as user_coupon_id', 'user_coupon.created_at as user_coupon_created_at', 'coupon.*')
                        ->leftJoin('coupon', 'user_coupon.coupon_id', '=', 'coupon.id')
                        ->where('user_coupon.id', $user_coupon_id)
                        ->where('user_id', $user_id)
                        ->whereNull('use_time')
                        ->first();
//dd($coupons->toArray());
        if (empty($coupons)) {
            throw new CouponServiceException("该优惠券不可用");

        }//end if()

        $deleted_at = $coupons->deleted_at;
        $start_time = $coupons->start_time;
        $end_time = $coupons->end_time;

        if(!empty($deleted_at)){

            throw new CouponServiceException("该优惠券已失效");
        }//end if()

        $current_time = date('Y-m-d H:i:s', time());

        if($start_time>$current_time){

            throw new CouponServiceException("该优惠券还未到使用日期");
        }//end if()

        if($current_time>$end_time){

            throw new CouponServiceException("该优惠券已过期");
        }//end if()

        $user_coupon = UserCoupon::where('id', $user_coupon_id)
                        ->where('user_id', $user_id)
                        ->update(['use_time'=>$current_time]);

        return $user_coupon;   //成功返回1


    }//end func useCoupon


    /**
     * 获取用户的优惠券(没有已经删除的优惠券)
     * @param  [type] $user_id [用户id]
     * @return [type] $user_id [优惠券类型：1：全场通用；2：商品；3：分类；4：店铺；5：品牌]
     */
    public function getUserCoupon($user_id, $search='',$returnPaginate=true){

        if (empty($user_id)) {
            throw new CouponServiceException("用户id不能为空");

        }//end if()

        $query = UserCoupon::leftJoin('coupon', 'user_coupon.coupon_id', '=', 'coupon.id')
                ->select('user_coupon.id as user_coupon_id', 'user_coupon.created_at as user_coupon_created_at', 'user_coupon.deleted_at as user_coupon_deleted_at','user_coupon.use_time as user_coupon_use_time', 'coupon.*');
        $query = $query->whereNull('user_coupon.deleted_at');
        $query = $query->where('user_id', $user_id);

        /*if (!empty($type) && $type != 'all') {
            $query = $query->where('type', $type);
            $search['type'] = $type;
        }//end if()*/

        if (!empty($search)) {

            foreach ($search as $key => $value) {

                if ($key=='type' && $value == 'all') continue;

                if ($key=='type_status'){

                    $current_time = date('Y-m-d H:i:s');

                    switch ($value) {

                        //未使用
                        case '1':

                            $query = $query->whereNull('use_time');

                            $query = $query->where('coupon.start_time', '<', $current_time);

                            $query = $query->where('coupon.end_time', '>', $current_time);

                            break;

                        //已使用
                        case '2':

                            $query = $query->whereNotNull('use_time');

                            break;

                        //已过期
                        case '3':

                            $query = $query->whereNull('use_time');

                            $query = $query->where('coupon.end_time', '<', $current_time);

                            break;

                        default:

                            break;
                    }
                }else{

                    $query = $query->where($key, $value);
                }

            }//end foreach()

        }//end if()

        if ($returnPaginate){

            return $query->paginate(10);

        }else{
            return $query->get();
        }

    }//end func getUserCoupon


    /**
     * 根据商品id获取用户可领取的优惠券
     *
     * @param  int $goods_id [商品id]
     * @return [type]        [description]
     */
    public function getCanReceiveCoupon($goods_id)
    {
        $current_time = date('Y-m-d H:i:s');
        //根据商品id获取商品信息
        $goods = Goods::find($goods_id);

        if ($goods) {
            /*$goods_cat_id = $goods->cat_id;
            $goods_shop_id = $goods->shop_id;
            $goods_brand_id = $goods->brand_id;*/

            //根据商品id、商品所属分类、商品所属店铺、商品所属品牌获取对应的可用的优惠券

            $query = Coupon::orderBy('coupon.type', 'asc')
                                ->leftJoin('coupon_type', 'coupon.id', '=', 'coupon_type.coupon_id')
                                ->select('coupon.*', 'coupon_type.id as coupon_type_id', 'coupon_type.use_id as coupon_type_use_id');

            //$query = $query->where('coupon.end_time', '>', "$current_time");

            // $query = $query->whereRaw('coupon.end_time > now() and coupon.start_time <= now()');//已开始未结束

            //$query = $query->where('coupon.amount', '>', 'coupon.receive_amount');

            //$query = $query->where('coupon.type', 1);
            $query = $query->whereRaw("coupon.type = 1 and coupon.deleted_at is null and coupon.end_time > now() and coupon.start_time <= now()");
            if ($goods_id) {
                /*$query = $query->orWhere('coupon.type', 2);
                $query = $query->where('coupon_type.use_id', $goods_id);*/
                $query = $query->orWhereRaw("coupon.type = 2 and coupon_type.use_id = $goods_id and coupon.deleted_at is null and coupon.end_time > now() and coupon.start_time <= now()");
            }//end if()
            if ($goods->cat_id) {
                /*$query = $query->orWhere('coupon.type', 3);
                $query = $query->where('coupon_type.use_id', $goods->cat_id);*/
                $query = $query->orWhereRaw("coupon.type = 3 and coupon_type.use_id = $goods->cat_id and coupon.deleted_at is null and coupon.end_time > now() and coupon.start_time <= now()");
            }//end if()
            if ($goods->shop_id) {
                /*$query = $query->orWhere('coupon.type', 4);
                $query = $query->where('coupon_type.use_id', $goods->shop_id);*/
                $query = $query->orWhereRaw("coupon.type = 4 and coupon_type.use_id = $goods->shop_id and coupon.deleted_at is null and coupon.end_time > now() and coupon.start_time <= now()");
            }//end if()
            if ($goods->brand_id) {
                /*$query = $query->orWhere('coupon.type', 5);
                $query = $query->where('coupon_type.use_id', $goods->brand_id);*/
                $query = $query->orWhereRaw("coupon.type = 5 and coupon_type.use_id = $goods->brand_id and coupon.deleted_at is null and coupon.end_time > now() and coupon.start_time <= now()");
            }//end if()


            $coupons = $query->get();

            return $coupons;

        }else{
            //商品不存在
            //echo 'heeh';
            return null;
        }

    }//end func getCanReceiveCoupon()


    /**
     * 根据优惠券id获取用户领取过该优惠券的数量
     *
     * @param  int $goods_id [优惠券id]
     * @return [type]        [description]
     */
    public function getUserCouponNumber($coupon_id, $user_id){

        $user_coupons = UserCoupon::where('user_id', $user_id)->where('coupon_id', $coupon_id)->get();

        if ($user_coupons) {
            return $user_coupons->count();
        }//end if()

    }//end func getUserCouponNumber()



    /**
     * 根据优惠券id和用户id获取该优惠券的信息
     *
     * @param  int $goods_id [优惠券id]
     * @param  int $user_id  [用户id]
     * @return [type]        [description]
     */
    public function getUserCouponInfo($coupon_id, $user_id){

        $user_coupon = UserCoupon::where('user_id', $user_id)->where('id', $coupon_id)->whereNull('use_time')->first();
        if($user_coupon){


            $coupon= Coupon::find($user_coupon->coupon_id);

            if($coupon){

                $coupon_types = CouponType::where('coupon_id', $user_coupon->coupon_id)->get();

                if ($coupon_types) {

                    $coupon->coupon_types = $coupon_types;

                }
            }//end if()

            return $coupon;

        }//end if()
        return false;
    }//end func getUserCouponInfo()


    /**
     * 获取网站所有优惠券
     *
     * @param  int $search [查询条件数组]
     * @return [type]        [description]
     */
    public function getCoupon($search){

        $query = Coupon::orderBy('created_at', 'desc');
        $query = $query->whereNull('coupon.deleted_at');

        if (!empty($search)) {

            foreach ($search as $key => $value) {

                if ($key=='type' && $value == 'all') continue;
                $query = $query->where($key, $value);
            }//end foreach()

        }//end if()

        $coupons = $query->paginate(40);
        return $coupons;
    }//end func


    /**
     * 用户领取优惠券
     *
     * @param  int $user_id [用户id]
     * @param  int $coupon_id [优惠券id]
     * @return [type]        [description]
     */
    public function receiveCoupon($user_id, $coupon_id)
    {

        if (empty($user_id)) {

            throw new CouponServiceException("用户id不能为空");
        }//end if()

        if (empty($coupon_id)) {

            throw new CouponServiceException("优惠券id不能为空");
        }//end if()

        $user_coupon_arr = [];
        $current_time = date('Y-m-d H:i:s');

            $coupon = Coupon::find($coupon_id);
            if(empty($coupon)){

                throw new CouponServiceException("优惠券不存在");
            }//end if()

            $receive_amount = $coupon->receive_amount;
            if($receive_amount>=$coupon->amount){

                throw new CouponServiceException("该优惠券已被领完");
            }//end if()

            if ($current_time>$coupon->end_time) {

                throw new CouponServiceException("优惠券已过期");
            }//end if()


            $user_coupons = UserCoupon::where('user_id', $user_id)->where('coupon_id', $coupon_id)->withTrashed()->get();

            if ($user_coupons->count()>0) {

                throw new CouponServiceException("该优惠券已经领取过了");
            }//end if()

            $user_coupon_arr['user_id'] = $user_id;
            $user_coupon_arr['coupon_id'] = $coupon_id;
            $user_coupon_arr['created_at'] = time();

        try {

            $user_coupon = UserCoupon::create($user_coupon_arr);

            if ($user_coupon->id) {

                $coupon->receive_amount = ++$receive_amount;
                $coupon->save();

                return $user_coupon->id;

            }//end if()

        } catch (CouponServiceException $e) {

            throw new CouponServiceException("领取优惠券失败");
        }


    }//end func receiveCoupon()

    /**
     * 删除用户优惠券
     *
     * @param  int $user_id [用户id]
     * @param  int $coupon_id [优惠券id]
     * @return [type]        [description]
     */
    public function destroyMyCoupon($user_id, $coupon_id)
    {


        if (empty($user_id)) {

            throw new CouponServiceException("用户id不能为空");
        }//end if()

        if (empty($coupon_id)) {

            throw new CouponServiceException("优惠券coupon_id不能为空");
        }//end if()

        $query = UserCoupon::leftJoin('coupon', 'user_coupon.coupon_id', '=', 'coupon.id')
                ->select('user_coupon.id as user_coupon_id', 'user_coupon.created_at as user_coupon_created_at', 'user_coupon.deleted_at as user_coupon_deleted_at','user_coupon.use_time as user_coupon_use_time', 'coupon.*');
        $query = $query->whereNull('user_coupon.deleted_at');
        $query = $query->where('user_id', $user_id);
        $query = $query->where('user_coupon.id', $coupon_id);

        // $user_coupons = $query->update(['deleted_at'=>null]);
        $user_coupons = $query->get();

        if ($user_coupons->count()) {

            foreach ($user_coupons as $key => $value) {

                $use_time = $value->user_coupon_use_time;

                $start_time = $value->start_time;

                $end_time = $value->end_time;
            }


            $current_time = date('Y-m-d H:i:s');

            if (($current_time<$start_time || $current_time>$end_time) || !empty($use_time)) {

                $user_coupon = UserCoupon::where('user_id', $user_id)->where('id', $coupon_id)->delete();

                return $user_coupon;

            }else{

                throw new CouponServiceException('只有已过期和已使用的优惠券才能删除');
            }
        }else{

            throw new CouponServiceException('优惠券不存在或已删除');
        }

        /*$user_coupon = UserCoupon::where('user_id', $user_id)->where('id', $coupon_id)->delete();

        return $user_coupon;*/
    }//end func destroyMyCoupon()

    /**
     * 根据条件获取用户优惠券数量
     *
     * @param  int $user_id [用户id]
     * @param  int $search  [查询条件数组]
     * @return [type]        [description]
     */
    /*public function statisticsCount($user_id, $search){

    }//end func statisticsCount*/


    /**
     * 根据条件获取用户优惠券
     *
     * @param  int $user_id [用户id]
     * @param  int $coupon_status  [查询条件,默认：所有未删除的； can_use：未使用；used：已使用；expired：已失效；deleted：已删除]
     * @return [type]        [description]
     */
    public function getCouponByStatus($user_id, $coupon_status=null){

        if (empty($user_id)) {

            throw new CouponServiceException("用户id不能为空");
        }//end if()

        $query = UserCoupon::orderBy('coupon.created_at', 'desc')
                                    ->select('coupon.*', 'user_coupon.id as user_coupon.id', 'user_coupon.use_time as user_coupon.use_time', 'user_coupon.created_at as user_coupon_created_at', 'user_coupon.deleted_at as user_coupon_deleted_at')
                                    ->where('user_id', $user_id)
                                    ->leftJoin('coupon', 'user_coupon.coupon_id', '=', 'coupon.id' );

        try {

            if (!empty($coupon_status)) {

                switch ($coupon_status) {

                    case 'can_use':
                        // echo '未使用';
                        // $query = $query->whereNull('user_coupon.use_time')->where('coupon.end_time', '>=', date('Y-m-d H:i:s'));
                        $query = $query->whereNull('user_coupon.use_time')->whereRaw('coupon.end_time >= now()');//未结束
                        break;

                    case 'used':
                        // echo '已使用';
                        $query = $query->whereNotNull('user_coupon.use_time');
                        break;

                    case 'expired':
                        // echo '已失效';
                        // $query = $query->whereNull('user_coupon.use_time')->where('coupon.end_time', '<', date('Y-m-d H:i:s'));
                        $query = $query->whereNull('user_coupon.use_time')->whereRaw('coupon.end_time < now()');
                        break;

                    case 'deleted':
                        // echo '已删除';
                        $query = $query->onlyTrashed();
                        break;
                }
            }//end if()

            $user_coupon = $query->get();

            return $user_coupon;

        } catch (CouponServiceException $e) {

            throw new CouponServiceException("查询失败");
        }
    }


}//end class